﻿using Aliyun.OSS;
using Furion;
using Furion.DependencyInjection;
using Furion.FriendlyException;
using HOPU.OnlineSchool.Application.FileUploads.Dtos;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace HOPU.OnlineSchool.Application.FileUploads.Services
{
    public class FileService : IFileService, ITransient
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="file"></param>
        /// <param name="host"></param>
        /// <returns></returns>
        public OssUploadOutput Upload(IFormFile file, string host)
        {
            //读取配置文件中的阿里云OSS配置信息
            string accessKeyId = App.Configuration["AliyunOss:AccessKeyId"];
            string accessKeySecret = App.Configuration["AliyunOss:AccessKeySecret"];
            string endpoint = App.Configuration["AliyunOss:Endpoint"];

            //允许的图片后缀名格式
            string[] allowExts = { ".jpg", ".png", "gif", "jpeg" };
            string bucketName = App.Configuration["AliyunOss:BucketName"];
            string newName = string.Empty;
            string ext = Path.GetExtension(file.FileName);

            //判断图片的后缀名是否合法
            if (!allowExts.Contains(ext))
                throw Oops.Oh("请上传.jpg、.png、.gif、.jpeg格式的图片！");

            //生成图片名称
            newName = YitIdHelper.NextId().ToString();

            //判断图片的大小是否小于1M
            if (file.Length / 1024 / 1024 > 1)
                throw Oops.Oh("上传的图片不能大于1M！");

            string path = $"{host}/" + DateTime.Now.ToString("yyyy/MM/dd") + "/" + newName + ext;
            OssClient client = new OssClient(endpoint, accessKeyId, accessKeySecret);
            // 上传文件。
            var fs = file.OpenReadStream();
            var result = client.PutObject(bucketName, path, file.OpenReadStream());
            fs.Dispose();

            //判断上传是否成功
            if (result.HttpStatusCode == HttpStatusCode.OK)
            {
                //返回上传成功后的图片路径
                string url = $"https://{bucketName}.{endpoint}/{path}";
                return new OssUploadOutput() { OssUrl = url };
            }
            else
            {
                throw Oops.Oh("上传失败");
            }

        }
    }
}
